// 网络是否在线
import { onUnmounted } from "vue"
import { useBoolean } from "./useBoolean"

interface IUseOnline {
  onOnLine?: () => any;
  onOffline?: () => any;
}

export function useOnline({ onOnLine, onOffline }: IUseOnline = {}) {
  const { bool, setFalse, setTrue } = useBoolean(navigator.onLine);

  function _onOnline() {
    setTrue();
    onOnLine && onOnLine();
  }

  function _onOffline() {
    setFalse();
    onOffline && onOffline();
  }

  window.addEventListener('online', _onOnline);
  window.addEventListener('offline', _onOffline);

  onUnmounted(() => {
    window.removeEventListener('online', _onOnline);
    window.removeEventListener('offline', _onOffline);
  })

  return bool
}